import axios from "axios";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import apiBase from "../api/base";

const service = axios.create({
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

service.defaults.baseURL = apiBase.development;

// 请求拦截器
const request = (config) => {
  nprogress.start();
  const token =
    localStorage.usertoken !== "undefined" ? localStorage.usertoken : "";
  if (token) {
    service.defaults.headers.common.Authorization = token;
  } else {
    delete service.defaults.headers.common.Authorization;
  }
  return config;
};

const request_err = (err) => {
  nprogress.start();
  console.log(err);
  return Promise.error(err);
};

// 响应拦截器
const response = (res) => {
  nprogress.done();
  if (res.status === 200 || res.status === 201) {
    return Promise.resolve(res);
  }
  return Promise.reject(res);
};

const response_err = (err) => {
  nprogress.done();
  if (err.status) {
    switch (err.status) {
      case 401: // 未登录
        break;
      case 403: // token 过期
        break;
      case 404: // 请求不存在
        break;
      default:
        break;
    }
  }
  return Promise.reject(err);
};

service.interceptors.request.use(request, request_err);
service.interceptors.response.use(response, response_err);

export default service;
